package com.xunwulian.weixin.h5.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xunwulian.api.iface.CardAPI;
import com.xunwulian.api.iface.SmsAPI;
import com.xunwulian.base.bean.SmsPocessorEntity4WeiXin;
import com.xunwulian.base.constant.ConstantBean;
import com.xunwulian.base.entity.CardInfoEntity;
import com.xunwulian.base.entity.Page;
import com.xunwulian.base.entity.SmsPocessorEntity;
import com.xunwulian.base.util.DateStyle;
import com.xunwulian.base.util.DateUtil;
import com.xunwulian.weixin.h5.constant.ResultType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 收发
 */
@RestController
@RequestMapping(value = "/appbusi")
public class IntAppbusiController {

    private static final Logger logger = LoggerFactory.getLogger(IntAppbusiController.class);

    @Reference
    private SmsAPI smsAPI;
    @Reference
    private CardAPI cardAPI;

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    /**
     * APP发送短信
     * <p>
     * MSISDN，CONTENT，USERID
     */
    @RequestMapping(value = "/sendmsg")
    @ResponseBody
    public Object sendmsg(@RequestParam("userId") String userId,
                          @RequestParam("msisdn") String msisdn,
                          @RequestParam("content") String content) {
        logger.info("APP发送短信, userId" + userId + ", msisdn:" + msisdn + ", content:" + content);

        CardInfoEntity entity = cardAPI.getByMsisdn(msisdn);

        if (entity == null) {
            logger.info("卡号不存在，msisdn:" + msisdn);
        } else if (!userId.equals(entity.getUserId()) && !userId.equals(entity.getSubUserId())) {
            logger.info("卡号不在用户名下，msisdn:" + msisdn + ", userId:" + userId);
        } else {
            smsAPI.send(userId, msisdn, content, entity.getAppId());
        }

        Map<String, Object> map = new HashMap();
        map.put("result", ResultType.SUCCESS.getType());

        return map;
    }

    /**
     * APP短信列表
     * <p>
     * 参数： USERID 用户ID, DATE_S 开始时间，DATE_E 结束时间
     */
    @RequestMapping(value = "/getmsg")
    @ResponseBody
    public Object getmsg(
            @RequestParam("userId") String userId,
            @RequestParam("msisdn") String msisdn,
            @RequestParam("pno") int pno,
            @RequestParam("psize") int psize) {

        logger.info("APP短信列表");

        Page page = new Page();
        page.setShowCount(psize);
        page.setCurrentPage(pno);

        String appId = ConstantBean.DEFAULT_APPID;

        List<SmsPocessorEntity> list = (List<SmsPocessorEntity>) smsAPI.listPage(page, appId, userId, msisdn, null, 0).getData();

        List<SmsPocessorEntity4WeiXin> weixinList = new LinkedList<>();

        for (SmsPocessorEntity p : list) {
            SmsPocessorEntity4WeiXin entity = new SmsPocessorEntity4WeiXin(p.getMsisdn(),
                    p.getType(), p.getContent(), DateUtil.DateToString(p.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            weixinList.add(0, entity);
        }
        Map<String, Object> map = new HashMap();

        logger.info("weixinList:" + gson.toJson(weixinList));

        // 总的记录数
        map.put("totalPageNum", page.getTotalResult());
        map.put("totalResultNum", page.getTotalPage());
        map.put("list", weixinList);
        map.put("result", ResultType.SUCCESS.getType());

        return map;
    }

    /**
     * 短信分组列表
     */
    @RequestMapping(value = "/getmsggroup")
    @ResponseBody
    public Object getmsggroup(@RequestParam("userId") String userId,
                              @RequestParam("pno") int pno,
                              @RequestParam("psize") int psize) {
        logger.info("短信分组列表, userId:" + userId);

        SortedMap<String, Object> resultMap = new TreeMap();
        resultMap.put("result", ResultType.SUCCESS.getType());

        // 分页信息
        Page page = new Page();
        page.setCurrentPage(pno);
        page.setShowCount(psize);

        List<SmsPocessorEntity> list = (List<SmsPocessorEntity>) smsAPI.listPage(page, null, userId, null, null, 0).getData();

        logger.info("SmsPocessorEntity list:" + gson.toJson(list));

        resultMap.put("dataList",
                list.stream().map(p -> new SmsPocessorEntity4WeiXin(p.getMsisdn(),
                        p.getType(),
                        p.getContent(),
                        DateUtil.DateToString(p.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS))
                ).collect(Collectors.toList()));

        // 总页数和总条数
        resultMap.put("totalPageNum", page.getTotalPage());
        resultMap.put("totalResultNum", page.getTotalResult());

        logger.info("map:" + gson.toJson(resultMap));

        return resultMap;
    }

}

